package io.keyss.view_record.recording

import android.graphics.Bitmap
import android.media.AudioFormat
import android.media.MediaCodec
import android.media.MediaFormat
import android.media.MediaRecorder
import android.util.Log
import android.view.View
import android.view.Window
import io.keyss.view_record.audio.AudioEncoder
import io.keyss.view_record.audio.GetAacData
import io.keyss.view_record.audio.GetMicrophoneData
import io.keyss.view_record.audio.MicrophoneManager
import io.keyss.view_record.base.Frame
import io.keyss.view_record.common.ConnectChecker
import io.keyss.view_record.common.VideoCodec
import io.keyss.view_record.recording.RecordController.Listener
import io.keyss.view_record.rtmp.rtmp.RtmpClient
import io.keyss.view_record.utils.RecordViewUtil
import io.keyss.view_record.utils.yuv.ConvertUtil
import io.keyss.view_record.video.EncoderErrorCallback
import io.keyss.view_record.video.FormatVideoEncoder
import io.keyss.view_record.video.GetVideoData
import io.keyss.view_record.video.IFrameDataGetter
import io.keyss.view_record.video.VideoEncoder
import java.nio.ByteBuffer

/**
 * Description: 采用pedro版本的编码类进行录制的一个版本
 *
 * Time: 2023/11/21 18:52
 * @author Key
 */



class ViewLiveRecorder {
    companion object {
        private const val TAG = "ViewRecordEncoder"
    }

    private lateinit var view: View
    private lateinit var window: Window

    @Volatile
    var isStartRecord = false
        private set

    private lateinit var videoEncoder: VideoEncoder
    private var videoInitSuccess = false

    private var audioInitSuccess = false
    private lateinit var audioEncoder: AudioEncoder
    private lateinit var microphoneManager: MicrophoneManager

    private lateinit var rtmpClient: RtmpClient
    @Throws
    fun initJustVideo(
        window: Window,
        view: View,
        width: Int,
        fps: Int = 24,
        videoBitRate: Int =  1080*1920,
        iFrameInterval: Int = 1,
    ) {
        check(!isStartRecord) { "Recording is already running" }
        this.window = window
        this.view = view
        
        // 华为设备特殊处理：使用更保守的默认参数
        val isHuaweiDevice = isHuaweiDevice()
        val adjustedFps = if (isHuaweiDevice) minOf(fps, 30) else fps
        val adjustedBitRate = if (isHuaweiDevice) minOf(videoBitRate, 4_000_000) else videoBitRate
        
        Log.d(TAG, "Device: ${if (isHuaweiDevice) "Huawei" else "Other"}, fps: $adjustedFps, bitRate: $adjustedBitRate")
        
        initVideoEncoder(width, adjustedFps, adjustedBitRate, iFrameInterval)
        initRtmpClient()
    }

    @Throws
    fun init(
        window: Window,
        view: View,
        width: Int,
        fps: Int = 60,
        videoBitRate: Int = 1080*1920,
        iFrameInterval: Int = 1,
        audioBitRate: Int = 192_000,
        audioSampleRate: Int = 44_100,
        isStereo: Boolean = true,
    ) {
        // 华为设备特殊处理：使用更保守的默认参数
        val isHuaweiDevice = isHuaweiDevice()
        val adjustedFps = if (isHuaweiDevice) minOf(fps, 30) else fps
        val adjustedBitRate = if (isHuaweiDevice) minOf(videoBitRate, 4_000_000) else videoBitRate
        
        Log.d(TAG, "Device: ${if (isHuaweiDevice) "Huawei" else "Other"}, fps: $adjustedFps, bitRate: $adjustedBitRate")
        
        initJustVideo(window, view, width, adjustedFps, adjustedBitRate, iFrameInterval)
        initAudioEncoder(audioBitRate, audioSampleRate, isStereo)
    }


    fun startLiveRecord(url: String?, statusListener: Listener, errorListener: EncoderErrorCallback) {
        check(videoInitSuccess) { "Video encoder is not initialized" }
        check(!isStartRecord) { "Recording is already running" }

        isStartRecord = true
        videoEncoder.setEncoderErrorCallback(errorListener)

        if (audioInitSuccess) {
            microphoneManager.start()
            audioEncoder.start()
        }
        videoEncoder.start()

        rtmpClient.connect(url)

    }

    private fun initVideoEncoder(width: Int, fps: Int, videoBitRate: Int, iFrameInterval: Int) {
        videoEncoder = VideoEncoder(object : GetVideoData {
            override fun onVideoInfo(sps: ByteBuffer, pps: ByteBuffer?, vps: ByteBuffer?) {
                rtmpClient.setVideoInfo(sps, pps, vps)
            }

            override fun getVideoData(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
                rtmpClient.sendVideo(h264Buffer, info)
            }

            override fun onVideoFormat(mediaFormat: MediaFormat) {
                Log.d(TAG, "Video format: $mediaFormat")
            }
        })

        videoEncoder.setFrameDataGetter(object : IFrameDataGetter {
            override fun getFrameData(): Frame {
                return Frame(getFrameBytes())
            }
        })

        val frameBitmap = getFrameBitmap(width)
        
        // 华为设备特殊处理：限制分辨率和码率
        val maxWidth = 1920
        val maxHeight = 1080
        val maxBitRate = 4_000_000 // 4Mbps，华为设备建议不超过4M
        
        // 计算合适的宽高比
        val aspectRatio = frameBitmap.width.toFloat() / frameBitmap.height.toFloat()
        
        // 确保宽度不超过最大值，并保持16的倍数
        var adjustedWidth = minOf(frameBitmap.width, maxWidth)
        adjustedWidth = (adjustedWidth + 15) and -16
        
        // 根据宽高比计算高度，并确保是16的倍数
        var adjustedHeight = (adjustedWidth / aspectRatio).toInt()
        adjustedHeight = (adjustedHeight + 15) and -16
        
        // 确保高度不超过最大值
        if (adjustedHeight > maxHeight) {
            adjustedHeight = maxHeight
            adjustedHeight = (adjustedHeight + 15) and -16
            adjustedWidth = (adjustedHeight * aspectRatio).toInt()
            adjustedWidth = (adjustedWidth + 15) and -16
        }
        
        // 确保最小分辨率
        if (adjustedWidth < 320) adjustedWidth = 320
        if (adjustedHeight < 240) adjustedHeight = 240
        
        // 限制帧率，华为设备建议不超过30fps
        val adjustedFps = minOf(fps, 30)
        
        // 限制码率
        val adjustedBitRate = minOf(videoBitRate, maxBitRate)
        
        Log.d(TAG, "Original size: ${frameBitmap.width}x${frameBitmap.height}")
        Log.d(TAG, "Adjusted size: ${adjustedWidth}x${adjustedHeight}")
        Log.d(TAG, "Adjusted fps: $adjustedFps, bitRate: $adjustedBitRate")
        
        // 测试颜色转换
        val conversionTest = ConvertUtil.testColorConversion()
        Log.d(TAG, "Color conversion test: $conversionTest")
        
        videoInitSuccess = videoEncoder.prepareVideoEncoder(
            adjustedWidth,
            adjustedHeight,
            adjustedFps,
            adjustedBitRate,
            iFrameInterval,
            FormatVideoEncoder.YUV420Dynamical
        )
        Log.d("xxxx","videoInitSuccess------->$videoInitSuccess")
    }

    private fun initAudioEncoder(audioBitRate: Int, audioSampleRate: Int, isStereo: Boolean) {
        audioEncoder = AudioEncoder(object : GetAacData {
            override fun getAacData(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) {
                rtmpClient.sendAudio(aacBuffer, info)
            }

            override fun onAudioFormat(mediaFormat: MediaFormat) {
                Log.d(TAG, "Audio format: $mediaFormat")
            }
        })
        audioEncoder.setRealTime(true)

        microphoneManager = MicrophoneManager(object : GetMicrophoneData {
            override fun inputPCMData(frame: Frame) {
                audioEncoder.inputPCMData(frame)
            }
        })

        audioInitSuccess = microphoneManager.createMicrophone(
            MediaRecorder.AudioSource.DEFAULT,
            audioSampleRate,
            isStereo,
            false,
            false
        )
        if (!audioInitSuccess) return

        audioInitSuccess = audioEncoder.prepareAudioEncoder(
            audioBitRate,
            microphoneManager.sampleRate,
            microphoneManager.channel == AudioFormat.CHANNEL_IN_STEREO,
            microphoneManager.inputBufferSize
        )
    }

    private fun initRtmpClient() {
        rtmpClient = RtmpClient(object : ConnectChecker {
            override fun onConnectionStarted(url: String) {
                Log.i(TAG, "RTMP connection started")
            }

            override fun onConnectionSuccess() {
                Log.i(TAG, "RTMP connection success")
            }

            override fun onConnectionFailed(reason: String) {
                Log.e(TAG, "RTMP connection failed: $reason")
            }

            override fun onAuthError() {
                Log.e(TAG, "RTMP auth error")
            }

            override fun onAuthSuccess() {
                Log.i(TAG, "RTMP auth success")
            }

            override fun onDisconnect() {
                Log.i(TAG, "RTMP disconnected")
            }

            override fun onNewBitrate(bitrate: Long) {
                Log.i(TAG, "RTMP new bitrate: $bitrate")
            }
        })
        rtmpClient.setVideoCodec(VideoCodec.H264)
        rtmpClient.setFps(videoEncoder.fps)
    }

    private fun getFrameBytes(): ByteArray {
        check(this::view.isInitialized && this::window.isInitialized) { "View or window is not initialized" }
        
        // 获取原始bitmap
        val originalBitmap = getFrameBitmap(videoEncoder.width)
        
        // 确保bitmap尺寸与编码器尺寸匹配
        val targetWidth = videoEncoder.width
        val targetHeight = videoEncoder.height
        
        val finalBitmap = if (originalBitmap.width != targetWidth || originalBitmap.height != targetHeight) {
            // 如果尺寸不匹配，进行缩放
            val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, targetWidth, targetHeight, true)
            originalBitmap.recycle() // 回收原始bitmap
            scaledBitmap
        } else {
            originalBitmap
        }
        
        val result = ConvertUtil.convertBitmapToYUVByteArray(finalBitmap, videoEncoder.formatVideoEncoder.formatCodec)
        
        // 回收bitmap
        if (finalBitmap != originalBitmap) {
            finalBitmap.recycle()
        }
        
        return result
    }

    private fun getFrameBitmap(width: Int): Bitmap {
        return RecordViewUtil.getBitmapFromView(window, view, width)
    }
    fun stopRecord() {
        if (!isStartRecord) return

        isStartRecord = false

        // 停止视频编码器
        if (::videoEncoder.isInitialized && videoInitSuccess) {
            videoEncoder.stop()
        }

        // 停止音频编码器和麦克风管理器
        if (::audioEncoder.isInitialized && audioInitSuccess) {
            audioEncoder.stop()
        }
        if (::microphoneManager.isInitialized && audioInitSuccess) {
            microphoneManager.stop()
        }

        // 断开 RTMP 客户端连接
        if (::rtmpClient.isInitialized) {
            rtmpClient.disconnect()
        }

        // 重置初始化状态
        videoInitSuccess = false
        audioInitSuccess = false
    }

    /**
     * 检测是否为华为设备
     */
    private fun isHuaweiDevice(): Boolean {
        val manufacturer = android.os.Build.MANUFACTURER.lowercase()
        val brand = android.os.Build.BRAND.lowercase()
        return manufacturer.contains("huawei") || brand.contains("huawei") || 
               manufacturer.contains("honor") || brand.contains("honor")
    }

}

